import { Injectable } from '@nestjs/common';
import { InjectRedis } from '@liaoliaots/nestjs-redis';
import Redis from 'ioredis';
import moment from 'moment-timezone';

@Injectable()
export class RedisCacheService {
    constructor(
        @InjectRedis() private readonly redis: Redis
    ) {}

    /**
     * @Description: 封装设置redis缓存的方法
     * @param key {String} key值
     * @param value {String} key的值
     * @param seconds {Number} 过期时间
     * @return: Promise<any>
     */
    public async set(key: string, value: string, seconds?: number): Promise<any> {
        return this.redis.set(key, value, 'EX', seconds);
    }


    /**
     * @Description: 设置获取redis缓存中的值
     * @param key {String}
     */
    public async get(key: string): Promise<string> {
        return this.redis.get(key);
    }

    /**
     * @Description: 根据key删除redis缓存数据
     * @param key {String}
     * @return:
     */
    public async del(key: string): Promise<any> {
        await this.redis.del(key);
    }

    /**
     * @Description: 给key累加一个计数
     * @param key {String}
     */
    public async incr(key: string): Promise<any> {
        const value = await this.redis.get(key);

        if (value) {
            const a = parseInt(value, 10);
            if (isNaN(a)) {
                throw new Error(`Value for key ${key} is not an integer`);
            }
            return this.redis.incr(key);
        }

        // 获取东八区当前日期的午夜时间
        const midnightInShanghai = moment().tz('Asia/Shanghai').endOf('day');
        // 获取当前时间
        const currentTimeInShanghai = moment().tz('Asia/Shanghai');
        // 计算差值（单位：秒）
        let secondsDifference = midnightInShanghai.diff(currentTimeInShanghai, 'seconds');
        if(secondsDifference <= 0){
            secondsDifference = 5;
        }

        this.redis.set(key, 1, "EX",secondsDifference);
        return 1;
    }

    /**
     * @Description: 给key减少一个计数
     * @param key {String}
     */
    public async decr(key: string): Promise<any> {
        const value = await this.redis.get(key);

        if (value) {
            const a = parseInt(value, 10);
            if (isNaN(a)) {
                throw new Error(`Value for key ${key} is not an integer`);
            }
            return this.redis.decr(key);
        }
    }

    /**
     * @Description: 给key设置在某个时间戳（秒）过期
     * @param key {String}
     * @param timestamp {Number}
     */
    public async expireAt(key: string, timestamp: number): Promise<any> {
        await this.redis.expireat(key, timestamp);
    }
}
